<?php

class UserGroupAction extends PublicAction
{

    function index()
    {
        $list = M('UserGroup')->select();

        foreach($list as $key=>$val){
            $list[$key]['amount'] = M('User')->where('group_id='.$val['id'])->count('id');
        }

        $this->assign('list', $list);
        $this->display();
    }

    function add()
    {
        if (IS_POST) {
            $model = D ('UserGroup');

            if (false === $model->create ()) {
                $this->error ( $model->getError () );
            }

            $typeid = $model->add() ;

            if($typeid) {
                $this->success(L('add_ok'), cookie('__forward__'));
            } else {
                $this->error(L('add_error').': '.$model->getDbError());
            }
        } else {
            $this->display();
        }
    }


    function edit()
    {
        $model = M('UserGroup');

        if (IS_POST) {
            $model = D('UserGroup');

            if (false === $model->create()) {
                $this->error( $model->getError() );
            }

            if ($model->save()) {
                $this->success('修改成功！', cookie('__forward__'));
            }else{
                $this->error('修改失败！');
            }
        } else {
            $id = $_GET['id'];

            $vo = $model->find($id);

            $this->assign('vo', $vo);
            $this->display();
        }
    }

    function delete()
    {
        $db = M('UserGroup');
        $id = I('get.id');
        if (!$id) {
            $this->error('参数不正确！');
        }
        $count = M('User')->where('level='.$id)->count('id');
        if ($count) {
            $this->error('该会员组下有会员，不能删除！');
        }
        if(false !== $db->delete($id)){
            $this->success('删除成功！');
        }else{
            $this->error('删除失败: '.$db->getDbError());
        }
    }
}